<?php

namespace app\wechat\controller\swoole;

use app\wechat\controller\Openid;
use app\wechat\controller\Platform;
use EasyWeChat\Kernel\Exceptions\HttpException;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use think\Exception;
use think\facade\Log;

// swoole服务端
class Server
{
    public $platform;

    public function start()
    {
        echo "客服消息发送服务端开启\n";

        // 创建Server对象，监听 127.0.0.1:9501端口
        $server = new \swoole_server("127.0.0.1", 9501);
        $this->platform = new Platform();

        // 不超时
        ini_set('default_socket_timeout', -1);

        // swoole配置
        $server->set(array(
//            'daemonize' => 1, // 守护进程
            'worker_num' => 4, // worker进程数 CPU核数1-4倍
            'log_file' => '/www/wwwroot/wechat.nanxuncn.cn/runtime/log/swoole.log', // 日志文件路径
            'task_worker_num' => 80, // task进程数
        ));

        //监听连接进入事件
        $server->on('connect', function ($serv, $fd) {
            echo "客户端连接.\n";
        });

        //监听数据接收事件
        $server->on('receive', function ($serv, $fd, $from_id, $data) {
            $openid_redis = new Openid();
            $arr = json_decode($data, true);
            $appid = $arr['appid'];

            echo $appid;
            if ($appid != '') {
                // 循环发送
                $openid = $openid_redis->pop_openid($appid);
                while ($openid) {
                    $arr['openid'] = $openid;
                    $serv->task($arr);
                    $openid = $openid_redis->pop_openid($appid);
                }
            }
        });

        // 异步任务
        $server->on('task', function ($serv, $task_id, $from_id, $data) {
            $appid = $data['appid'];
            $refresh_token = $data['refresh_token'];
            $item = $data['item'];
            $openid = $data['openid'];

            try {
                $gh = $this->platform->getGhWithToken($appid, $refresh_token);
                $msg = $this->handle_news($item);

                $result = $gh->customer_service->message($msg)->to($openid)->send();

                if ($result['errcode'] == 0) {
                    $openid_redis = new Openid(true);
                    $openid_redis->count($appid, $openid);
                }
            } catch (HttpException $exception) {
                return;
            } catch (Exception $exception) {
                return;
            }
        });

        //监听连接关闭事件
        $server->on('close', function ($serv, $fd) {
            echo "客户端关闭.\n";
        });

        //启动服务器
        $server->start();
    }

    // 处理图片链接消息
    public function handle_news($item)
    {
        $new = [
            new NewsItem([
                'title' => $item['title'],
                'description' => '',
                'url' => $item['url'],
                'image' => $item['image'],
            ])
        ];
        return new News($new);
    }
}

$server = new Server();
$server->start();
